package com.xinyue.server.framework.server.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.xinyue.server.framework.handler.GameServerEncryptService;
import com.xinyue.server.framework.message.GameMessagePackage;
import com.xinyue.server.framework.server.common.GameMessageCodecService;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

/**
 * 游戏网络通信编码Handler，负责处理向网络层发送消息之前，将消息序列化为ByteBuf
 *
 * @Author 王广帅
 * @Date 2021/5/30 19:12
 */
public class SocketEncoderHandler extends ChannelOutboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(SocketEncoderHandler.class);


    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        try {
            if (msg instanceof GameMessagePackage) {
                GameMessagePackage response = (GameMessagePackage) msg;
                byte[] aesKey = GameServerEncryptService.getAesKey(ctx.channel());
                ByteBuf byteBuf = GameMessageCodecService.encode(response, aesKey);
                ctx.write(byteBuf, promise);

            } else {
                super.write(ctx, msg, promise);
            }
        } catch (Throwable e) {
            logger.error("消息响应异常，message: {}", JSON.toJSONString(msg), e);
        }
    }

}
